<template>
  <div class="app-container">
<!--    <el-row :gutter="10" class="mb20">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['enterprise:deliveryOrder:add']"-->
<!--        >新增-->
<!--        </el-button-->
<!--        >-->
<!--      </el-col>-->
<!--      <right-toolbar-->
<!--        :showSearch.sync="showSearch"-->
<!--        @queryTable="getList"-->
<!--      ></right-toolbar>-->
<!--    </el-row>-->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="房间" prop="premisesAddress">
        <el-input v-model="queryParams.premisesAddress" placeholder="请输入房间" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="deliveryOrderStatus">
        <el-select
          v-model="queryParams.deliveryOrderStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in dict.type.delivery_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['enterprise:lesseeContract:query']"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="单号" prop="deliveryOrderId"/>
      <el-table-column label="房间" prop="premisesAddress"/>
      <el-table-column label="签署方式" prop="signingMode">
        <template #default="scope">
          <dict-tag
            :options="dict.type.delivery_signing_mode"
            :value="scope.row.signingMode"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="最晚签约日期"
        align="center"
        prop="latestSigningTime"
      >
      </el-table-column>
      <el-table-column label="类型" prop="deliveryOrderType">
        <template #default="scope">
          {{ scope.row.deliveryOrderType === '1'?'交房':scope.row.deliveryOrderType === '2'?'租房':'' }}
        </template>
      </el-table-column>
      <el-table-column
        label="发起时间"
        align="center"
        prop="createTime"
      >
      </el-table-column>
      <el-table-column
        label="发起人"
        align="center"
        prop="createBy"
      >
      </el-table-column>
      <el-table-column label="状态" prop="deliveryOrderStatus">
        <template #default="scope">
          <dict-tag
            :options="dict.type.delivery_order_status"
            :value="scope.row.deliveryOrderStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['enterprise:deliveryOrder:query']"
          >查看合同
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleSignProgress(scope.row)"
            v-hasPermi="['enterprise:deliveryOrder:list']"
          >签署进度
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleSign(scope.row)"
            v-hasPermi="['enterprise:deliveryOrder:list']"
            v-if="scope.row.deliveryOrderStatus === '1' "
          >合同签署
          </el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            @click="handleDownload(scope.row)"-->
<!--            v-hasPermi="['enterprise:lesseeContract:signing']"-->
<!--            v-if="scope.row.contractType != 3 && scope.row.lesseeContractStatus == 2"-->
<!--          >下载合同-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            @click="handleUpload(scope.row)"-->
<!--            v-hasPermi="['enterprise:lesseeContract:signing']"-->
<!--            v-if="scope.row.contractType != 3 && scope.row.lesseeContractStatus == 2"-->
<!--          >上传合同-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            @click="handleRepeal(scope.row)"-->
<!--            v-hasPermi="['enterprise:lesseeContract:signing']"-->
<!--            v-if="scope.row.lesseeContractStatus == 1 || scope.row.lesseeContractStatus == 2"-->
<!--          >撤销-->
<!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            @click="handleRelaunch(scope.row)"
            v-hasPermi="['enterprise:deliveryOrder:edit']"
            v-if="scope.row.deliveryOrderStatus === '4'"
          >重新发起
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增 -->
    <Add v-model="addDialogVisible" :title="title" @success="handleQuery" :form-data="form"/>
    <!-- 签署进度 -->
    <SignProgress
      v-model="signProgressDialogVisible" :title="title" :data="form" keyName="deliveryOrderId"
    />
    <!-- 查看 -->
    <ViewContract :data="form" :title="title" v-model="viewDialogVisible"/>
    <!-- 上传合同 -->
    <UploadContract v-model="uploadContractDialogVisible" :title="title" :data="form" @success="handleQuery"/>
    <!-- 重新发起 -->
    <Add v-model="relaunchDialogVisible" :title="title" @success="handleQuery" :form-data="form" :isRelaunch="true"/>
  </div>
</template>

<script>

import Add from './components/add.vue'
import SignProgress from './components/sign-progress.vue'
import ViewContract from './components/view-contract.vue'
import UploadContract from '@/views/long-short-rent/contract/lessee/components/upload-contract.vue'
import {
  getLesseeContract,
  listLesseeContract,
  listLesseeSource,
  repealLesseeContract, getAllLesseeContract, exportLesseeContract, signLesseeContract
} from '@/api/contract/lessee'
import { getDeliveryOrderList, getPreviewUrl, signContract } from '@/api/contract/deliveryOrder'

export default {
  name: 'contract',
  dicts: [ 'delivery_signing_mode','lessee_signing_mode','delivery_order_status'],
  components: {
    Add,
    SignProgress,
    ViewContract,
    UploadContract
  },
  data() {
    return {
      //统计数据
      statistics: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      list: [],
      // 弹出层标题
      title: '',
      //表格行id
      id: undefined,
      //是否详情页
      isDetail: false,
      // 是否显示弹出层
      open: false,
      // 当前选择
      current: '0',
      // 日期范围
      dateRange: [],
      // 是否显示新建合同弹窗
      addDialogVisible: false,
      // 是否显示合同详情弹窗
      detailDialogVisible: false,
      // 是否显示签署进度弹窗
      signProgressDialogVisible: false,
      // 是否显示查看弹窗
      viewDialogVisible: false,
      // 是否显示上传合同弹窗
      uploadContractDialogVisible: false,
      // 是否显示重新发起弹窗
      relaunchDialogVisible: false,
      src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        premisesAddress: undefined, // 房间地址
        deliveryOrderStatus: undefined, // 交割单状态:1.签署中;2.签署完成;3.已终止;4.已逾期（字典：delivery_order_status）
        // contractType: undefined //合同分类:1.个人纸质合同;2.企业纸质合同;3.个人电子合同;
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 签署方式映射 签署方式:1.平台与租客签约;2.业主与租客签约
      signingModeMap: {
        '1': '平台与租客签约',
        '2': '业主与租客签约'
      },
      lesseeSourceList: []
    }
  },
  computed: {
  },
  created() {
    this.getList()
    this.getLesseeSourceList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      getDeliveryOrderList(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.list = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    getLesseeSourceList() {
      listLesseeSource().then(
        (response) => {
          this.lesseeSourceList = response.data
        }
      )
    },
    // 表单重置
    reset() {
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      console.log('reset',this.resetForm('queryForm'))
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.contractId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.addDialogVisible = true
      this.title = '新增租客合同'
    },
    /** 查看按钮操作 */
    handleView(row) {

      let params = {
        deliveryOrderId: row.deliveryOrderId,
        // redirectUrl: ''
      }
      getPreviewUrl(params).then(
        (response) => {
          window.open(response.data)
        }
      )
    },
    // 签署进度
    handleSignProgress(row) {
      this.title = '签署进度'
      this.form = { ...row }
      this.signProgressDialogVisible = true
    },
    // 合同签署
    handleSign(row) {
      let params = {
        deliveryOrderId: row.deliveryOrderId,
        redirectUrl: ''
      }
      signContract(params).then((response) => {
        window.open(response.data)
      })
    },
    // 下载合同
    handleDownload(row) {
      let params = {
        deliveryOrderId: row.deliveryOrderId
      }
      this.download(
        '/enterprise/contract/lesseeContract/export',
        {
          ...params
        },
        `${row.contractTemplateName}.doc`
      )
    },
    // 上传合同
    handleUpload(row) {
      this.form = { ...row }
      this.title = '上传合同'
      this.uploadContractDialogVisible = true
    },
    // 撤销
    handleRepeal(row) {
      this.$confirm('确定撤销该合同吗？').then(() => {
        // 调用撤销接口
        return repealLesseeContract({ deliveryOrderId: row.deliveryOrderId }).then((res) => {
          this.$message.success(res.msg)
          this.getList()
        }).catch(() => {
          this.$message.error('撤销失败')
        })
      }).catch(() => {
        console.log('取消撤销')
      })
    },
    // 重新发起
    handleRelaunch(row) {
      // getAllLesseeContract(row.deliveryOrderId).then((res) => {
      //   this.form = { ...res.data }
      //   this.title = '重新发起'
      //   this.relaunchDialogVisible = true
      // })

      console.log('重新发起',row)
      this.form = { ...row }
      this.title = '重新发起'
      this.relaunchDialogVisible = true

    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  color: #666;
}

.total {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}

.left-border {
  border-left: 1px solid #999;
}

.right-border {
  border-right: 1px solid #999;
}

.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;

  span {
    color: #565c5f;
  }

  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}

.QR-code {
  padding: 30px;
  width: 100%;
  display: flex;
  justify-content: center
}
</style>
